﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;

using System.Text;
using System.Windows.Forms;
using QUANLYCHAMCONG.BL.Entities.Security;
using Hopthoai;
using QUANLYCHAMCONG.BL.BUS.Security;
using QUANLYCHAMCONG.BL.BUS;
using DgvFilterPopup;

namespace QUANLYCHAMCONG.PL.CMS.Hethong
{
    public partial class Users : UserControl
    {
        public delegate void _Close();
        public event _Close Close;
        USER user;
        int flag = 0;
        frmHoidap f;
        public Users()
        {
            InitializeComponent();
        }

        private void cmbnv_SelectedIndexChanged(object sender, EventArgs e)
        {

                bool IsDuplicate = true;
                if (cmbnv.SelectedIndex != -1 && cmbnv.SelectedValue.ToString() != "")
                {
                    user = new USER();
                    if (cmbnv.SelectedValue.ToString() != "System.Data.DataRowView")
                    {
                        if (this.flag == 1 || this.flag == 2)
                        {
                            user.MANV = cmbnv.SelectedValue.ToString();
                            IsDuplicate = USERBUS.IsExists(user);
                        }
                    }
                    else
                        return;
                    if (IsDuplicate == false)
                    {
                        f = new frmHoidap("Nhân viên này đã có username rồi!", frmHoidap.CO.an, frmHoidap.KHONG.an, frmHoidap.THOAT.an, frmHoidap.HINH.baoloi);
                        f.ShowDialog();

                    }
                }
        }

        private void txtusername_Leave(object sender, EventArgs e)
        {
            if (flag != 2)
            {
                // kiem tra viec trung username
                DataTable dt = new DataTable();
                if (!String.IsNullOrEmpty(txtusername.Text))
                {
                    user = new USER();
                    user.USERNAME = txtusername.Text;
                    dt = USERBUS.IsDuplicateUserName(user);
                    if (dt.Rows.Count != 0)
                    {
                        f = new frmHoidap("UserName đã tồn tại!", frmHoidap.CO.an, frmHoidap.KHONG.an, frmHoidap.THOAT.an, frmHoidap.HINH.baoloi);
                        f.ShowDialog();
                        txtusername.Focus();
                    }
                }
            }

        }
        private void SetLink()
        {
            this.links1.SetValues("Hệ thống", "Tạo tài khoản đăng nhập");
        }
        private void Event()
        {
            
            txtusername.Focus();
            this.toolbar1.Add += new Toolbar._Add(toolbar1_Add);
            this.toolbar1.Edit += new Toolbar._Edit(toolbar1_Edit);
            this.toolbar1.Save += new Toolbar._Save(Save);
            this.toolbar1.Delete += new Toolbar._Delete(toolbar1_Delete);
            this.toolbar1.Close += new Toolbar._Close(toolbar1_Close);
            this.toolbar1.Refresh += new Toolbar._Refesh(Refresh);
            InitGrid();
            LoadData();
        }
        void Refresh()
        {
            RemoveCheckbox();
            this.toolbar1.SetSave();
            this.flag = 0;
            this.dgvmenu.ReadOnly = true;
            this.dgvmenu.AllowUserToAddRows = true;
            LoadData();
            this.Clear();
        }
        void toolbar1_Close()
        {
            if (this.Close != null)
                this.Close();
        }
        private int FindAviable()
        {
            foreach (DataGridViewColumn dr in this.dgvmenu.Columns)
            {
                if (dr is DataGridViewCheckBoxColumn)
                    return 1;
            }
            return 0;
        }
        private void RemoveCheckbox()
        {
            if (FindAviable() == 1)
            {
                this.dgvmenu.Columns.RemoveAt(0);
                this.dgvmenu.Controls.RemoveByKey(((CheckBox)this.dgvmenu.Controls.Find("checkboxHeader", true)[0]).Name);
                LoadData();
            }
        }
        private void AddCheckbox(DataTable dt)
        {
            if (FindAviable() == 0)
            {
                DataGridViewCheckBoxColumn cb = new DataGridViewCheckBoxColumn();
                cb.Width = 30;
                cb.FillWeight = 30;
                cb.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                this.dgvmenu.Columns.Insert(0, cb);
                Rectangle rect = this.dgvmenu.GetCellDisplayRectangle(0, -1, true);
                rect.X = rect.Location.X + cb.Width / 33;
                CheckBox checkboxHeader = new CheckBox();
                checkboxHeader.Name = "checkboxHeader";
                checkboxHeader.Size = new Size(18, 18);
                checkboxHeader.Location = rect.Location;
                checkboxHeader.CheckedChanged += new EventHandler(checkboxHeader_CheckedChanged);
                this.dgvmenu.Controls.Add(checkboxHeader);
                this.dgvmenu.Columns[0].Width = 50;
                this.dgvmenu.DataSource = dt;
            }
        }
        void checkboxHeader_CheckedChanged(object sender, EventArgs e)
        {
            if (((CheckBox)this.dgvmenu.Controls.Find("checkboxHeader", true)[0]).Checked == true)
            {
                for (int i = 0; i < this.dgvmenu.RowCount; i++)
                {
                    this.dgvmenu[0, i].Value = ((CheckBox)this.dgvmenu.Controls.Find("checkboxHeader", true)[0]).Checked;
                }
            }
            else
            {
                for (int i = 0; i < this.dgvmenu.RowCount; i++)
                {
                    this.dgvmenu[0, i].Value = false;
                }
            }
        }
        void toolbar1_Delete()
        {
            flag = 3;
            this.dgvmenu.ReadOnly = false;
            this.dgvmenu.AllowUserToAddRows = false;
            this.toolbar1.SetAdd_Edit_Delete();
            AddCheckbox(USERBUS.SelectAll());

        }
        void toolbar1_Edit()
        {
            flag = 2;
            Clear();
            this.dgvmenu.Focus();
            this.dgvmenu.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            this.dgvmenu.Rows[0].Selected = true;
            this.dgvmenu.ReadOnly = false;
            this.dgvmenu.AllowUserToAddRows = false;
            this.toolbar1.SetAdd_Edit_Delete();
            this.cmbnv.Enabled = true;
        }
        void toolbar1_Add()
        {
            flag = 1;
            Clear();
            CreateID();
            this.toolbar1.SetAdd_Edit_Delete();
            txtusername.Focus();
            this.cmbnv.Enabled = true;

        }
        USER AddDuLieu(USER ts)
        {
            user.USERID = txtmauser.Text;
            user.USERNAME = txtusername.Text;
            user.PASSWORD = txtpassword.Text;
            user.CREATEDATE = DateTime.Now.Date;
            user.MANV = cmbnv.SelectedValue.ToString();
            user.GROUPID = cmbnhom.SelectedValue.ToString();
            return ts;
        }
        void Save()
        {
            //khoi tao
            user = new USER();
            if (flag == 1)
            {
                if (USERBUS.Insert(AddDuLieu(user)) == true)
                {
                    flag = 0;
                    f = new frmHoidap("Thêm Tên đăng nhập thành công!", frmHoidap.CO.an, frmHoidap.KHONG.an, frmHoidap.THOAT.an, frmHoidap.HINH.thongtin);
                    f.ShowDialog();
                    LoadData();
                    this.toolbar1.SetSave();
                    Clear();
                    this.cmbnv.Enabled = false;
                    
                }
                else
                {
                    flag = 0;
                    f = new frmHoidap("Thêm Tên đăng nhập  có lỗi xảy ra!", frmHoidap.CO.an, frmHoidap.KHONG.an, frmHoidap.THOAT.an, frmHoidap.HINH.thongtin);
                    f.ShowDialog();
                    LoadData();
                    
                    this.toolbar1.SetSave();
                    Clear();
                    this.cmbnv.Enabled = false;
                }
            }
            if (flag == 2)
            {
                try
                {
                    f = new frmHoidap("Bạn có muốn sửa Tên đăng nhập  ?", frmHoidap.CO.hien, frmHoidap.KHONG.hien, frmHoidap.THOAT.an, frmHoidap.HINH.thongtin);
                    if (f.ShowDialog() == DialogResult.Yes)
                    {
                        if (USERBUS.Update(AddDuLieu(user)) == true)
                        {
                            flag = 0;
                            f = new frmHoidap("Sửa Tên đăng nhập  thành công!", frmHoidap.CO.an, frmHoidap.KHONG.an, frmHoidap.THOAT.an, frmHoidap.HINH.thongtin);
                            f.ShowDialog();
                            LoadData();
                            this.dgvmenu.ReadOnly = true;
                            this.toolbar1.SetSave();
                            Clear();
                            this.cmbnv.Enabled = false;
                        }
                        else
                        {
                            flag = 0;
                            f = new frmHoidap("Có lỗi khi Sửa Tên đăng nhập  !", frmHoidap.CO.an, frmHoidap.KHONG.an, frmHoidap.THOAT.an, frmHoidap.HINH.thongtin);
                            f.ShowDialog();
                            this.toolbar1.SetSave();
                            this.dgvmenu.ReadOnly = true;
                            Clear();
                            this.cmbnv.Enabled = false;
                        }

                    }
                    else
                    {
                        this.dgvmenu.ReadOnly = true;
                        this.toolbar1.SetSave();
                        Clear();
                    }
                }
                catch { return; }
            }
            if (flag == 3)
            {
                f = new frmHoidap("Bạn có chắc chắn muốn xóa dữ liệu Tên đăng nhập  vừa chọn?", frmHoidap.CO.hien, frmHoidap.KHONG.hien, frmHoidap.THOAT.an, frmHoidap.HINH.dauhoi);
                if (f.ShowDialog() == DialogResult.Yes)
                {
                    foreach (DataGridViewRow dr in this.dgvmenu.Rows)
                    {
                        try
                        {
                            if (dr.Cells[0].Value != null)
                            {
                                user = new USER();
                                user.USERID = dr.Cells["USERID"].Value.ToString();
                                USERBUS.Delete(user);
                            }
                        }
                        catch
                        {
                            f = new frmHoidap("Bạn chưa chọn phần Tên đăng nhập  nào vui lòng chọn lại!", frmHoidap.CO.an, frmHoidap.KHONG.an, frmHoidap.THOAT.an, frmHoidap.HINH.thongtin);
                            f.ShowDialog();
                        }
                    }
                    f = new frmHoidap("Xóa thành công Tên đăng nhập !", frmHoidap.CO.an, frmHoidap.KHONG.an, frmHoidap.THOAT.an, frmHoidap.HINH.thongtin);
                    f.ShowDialog();
                    RemoveCheckbox();
                    this.toolbar1.SetSave();
                    this.dgvmenu.ReadOnly = true;
                    this.dgvmenu.AllowUserToAddRows = true;
                    
                }

            }

        }
        void CreateID()
        {
            user = new USER();
            this.txtmauser.Text = USERBUS.GetID();
        }
        private void Clear()
        {
            foreach (Control c in this.Controls)
            {
                if (c is Panel)
                    foreach (Control d in c.Controls)
                        if (d is TextBox)
                            d.Text = "";
            }
            cmbnv.SelectedIndex = 0;
           
        }
        void LoadData()
        {
            user = new USER();
            Common.HightLightDataGridViewRow(ref this.dgvmenu, USERBUS.SelectAll());
            this.dgvmenu.Columns["USERID"].FillWeight = 100;
            this.dgvmenu.Columns["PASSWORD"].Visible = false;
            LoadCombobox();
        }
        void LoadCombobox()
        { 
            //nhan vien
            this.cmbnv.DataSource = STAFFBUS.SelectAll();
            this.cmbnv.DisplayMember = "TENNV";
            this.cmbnv.ValueMember = "MANV";
            //group
            this.cmbnhom.DataSource = GROUPBUS.SelectAll();
            this.cmbnhom.DisplayMember = "GROUPNAME";
            this.cmbnhom.ValueMember = "GROUPID";
        }
        private void InitGrid()
        {
            DgvFilterManager f = new DgvFilterManager();
            f.DataGridView = (DataGridView)this.dgvmenu;
        }
        void ChooseData(object sender, int e)
        {
            if (flag == 2)
            {
                try
                {
                    this.dgvmenu.EndEdit();
                    DataGridViewRow dr = this.dgvmenu.Rows[e];
                    txtmauser.Text = dr.Cells["USERID"].Value.ToString();
                    txtusername.Text = dr.Cells["USERNAME"].Value.ToString();
                    txtpassword.Text = dr.Cells["PASSWORD"].Value.ToString();
                    cmbnv.SelectedIndex = cmbnv.FindString(dr.Cells["TENNV"].Value.ToString());
                    cmbnhom.SelectedIndex = cmbnhom.FindString(dr.Cells["GROUPNAME"].Value.ToString());
                }
                catch { return; };
            }
        }

        private void dgvmenu_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            ChooseData(sender, e.RowIndex);
        }

        private void dgvmenu_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
        {
            ChooseData(sender, 0);
        }

        private void dgvmenu_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            ChooseData(sender, e.RowIndex);
        }

        private void Users_Load(object sender, EventArgs e)
        {
            Event();
            SetLink();
        }

    }
}
